/*
* dataview 私有方法  网格列表
* */
const dvFunPrivateGrid = {

  //工具栏点击后
  toolbarButtonClickEvent(button) {
    button.key = button.code
    if (!this.utilDataview.toolbarButtonClickBefore(this, button)) return
    switch (button.key) {
    case 'closeWin':
      this.$emit('closewin')
      break
    case 'importData':
      this.utilPrint.openImport({viewKey: this.importViewKey})
      break
    case 'exportData':{
      this.getGrid().openExport()
      break
    }
    default:
      if (button.flagPrint && button.flagPrint == true) { //标准打印按钮
        if (this.strings.isBlank(button.printBusType)) {
          this.utilMessage.warning('该打印按钮未配置打印模板，请检查')
          return
        }
        let checkRows = this.$refs.tbMain.getCheckboxRecords()
        if (!checkRows || checkRows.length < 1) {
          this.utilMessage.warning('请选择需要打印的数据')
          return
        }
        let param = {
          'that': this, //当前调用对象
          configList: [ //打印配置，可以多个
          ]
        }
        checkRows.forEach(row => {
          //过滤条件
          let result = true
          //兼容 showCondition
          let data = row
          if (this.strings.isNotBlank(button.showCondition)) {
            try {
              result = eval(button.showCondition)
            } catch (e) {
              console.error('toolbarButtonClickEvent.evalerror')
              console.error(e)
              result = false
            }
          }
          if (result) {
            param.configList.push(
              {
                //打印配置
                printBusType: button.printBusType, //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: row, //数据对象
                formDataId: row.id,
              }
            )
          }
        })
        if (param.configList.length < 1) {
          this.utilMessage.warning('所选择【' + checkRows.length + '】，可打印【' + param.configList.length + '】')
          return
        }

        this.utilMessage.success('所选择【' + checkRows.length + '】，可打印【' + param.configList.length + '】', 3000)
        global.utilPrint.openFormPrint(param)
      } else {
        this.handleButton(button)
      }
      break
    }
  },
  // 获取主列表结构功能
  fetchStru(viewKey, autoReload = true) {
    if (this.propViewKey && this.strings.isBlank(viewKey)) viewKey = this.propViewKey
    if (!this.propViewKey && !viewKey) return
    if (!viewKey && typeof (viewKey) != 'string') this.listLoading = true
    this.isDataviewLoadStru = true
    this.isAutoReloadAfterFetchStru = autoReload

    // 流程相关配置
    if (this.strings.isNotBlank(this.propFlowKey)) {
      let flowGet = JSON.parse(JSON.stringify(global.utilVuex.getFlowMap()[this.propFlowKey]))
      if (!flowGet) {
        this.utilMessage.warning(`未找到相关流程配置【${this.propFlowKey}】,请刷新界面重试`)
        return
      }
      if (!flowGet.flowNodeList || flowGet.flowNodeList.length == 0) {
        this.utilMessage.warning(`未找到相关流程节点配置【${this.propFlowKey}】,请刷新界面重试`)
        return
      }
      flowGet.flowNodeList.sort((left, right) => {
        return this.strings.defaultIfBlank(left.sort, 999) - this.strings.defaultIfBlank(right.sort, 999)
      })
      if (this.flowNodeListFilterFun) {
        flowGet.flowNodeList = this.flowNodeListFilterFun(flowGet.flowNodeList)
      }

      if (!flowGet.flowButtonList || flowGet.flowButtonList.length == 0) {
        this.utilMessage.warning(`未找到相关流程按钮配置【${this.propFlowKey}】,请刷新界面重试`)
        return
      }
      this.flow = JSON.parse(JSON.stringify(flowGet))

      this.flowNodes = JSON.parse(JSON.stringify(flowGet.flowNodeList))
      this.viewFormFlowButtons = JSON.parse(JSON.stringify(flowGet.flowButtonList))

      //为了避免每个流程都增加作废节点，此处追加默认作废节点，当然了，流程配置时如果节点也指定了作废节点，将覆盖此处配置
      if (this.flowNodes.findIndex(ob => ob.value == 'close') == -1) {
        this.flowNodes.push(
          {
            color: '#E6A23C',
            value: 'close',
            sort: 999,
            id: 'close',
            name: '已作废',
            flagShowVfbAdd: false,
            flagShowVfbSave: false,
            flagShowVfbDelete: false,
            flagShowVbAdd: false,
            flagShowVbRefresh: false,
            flagShowVbDelete: false,
            flagShowVrbEdit: false,
            flagShowVrbDelete: false,
            flagShowVrbView: false,
          }
        )
      }
    }

    // 列表表单相关配置
    if (!global.utilVuex.getDataviewMap()[viewKey]) {
      this.utilMessage.warning(`未找到相关列表表单配置【${viewKey}】,请刷新界面重试`)
      return
    }
    let viewObj = JSON.parse(JSON.stringify(global.utilVuex.getDataviewMap()[viewKey]))
    this.formConfig = viewObj
    //  赋值：rows 行数据，columns 列定义，settings 配置信息（包括命令按钮等）
    if (this.propIsColumnEdit) {
      let index = 0
      viewObj.columns.forEach(column => {
        viewObj.columns[index].edit = this.propIsColumnEdit(viewObj.columns[index])
        if (!viewObj.columns[index].edit) {
         viewObj.columns[index].editRender = ''
        }
        index ++
      })
    }
    this.columns = this.utilDataview.getColumns(this, viewObj.columns)

    //是否包含流程字段，做判断使用
    if (this.columns && this.columns.length > 0) {
      let findIndex = this.columns.findIndex(column => column.name == 'flowStatus')
      if (findIndex != -1) this.haveFlowField = true

      //字段map
      this.columns.forEach(column => this.columnsMap[column.name] = column)
    }
    this.noPrintSeq = viewObj.noPrintSeq
    this.baseTable = viewObj.baseTable
    this.primaryKey = viewObj.primaryKey
    this.viewType = viewObj.viewType
    this.listEntry = viewObj.listEntry
    this.queryEntry = viewObj.queryEntry
    this.saveEntry = viewObj.saveEntry
    this.deleteEntry = viewObj.deleteEntry
    this.flowEntry = viewObj.flowEntry
    this.showCheckbox = viewObj.showCheckbox || false
    this.showRadiobox = viewObj.showRadiobox || false
    this.editable = viewObj.editable || false
    this.showPagination = viewObj.showPagination || false
    this.toolbars.showImport = viewObj.showImport || false
    this.toolbars.showExport = viewObj.showExport || false
    this.toolbars.showPrint = viewObj.showPrint || false
    this.toolbars.showMaxZoom = viewObj.showMaxZoom || false
    this.viewFormWidth = viewObj.viewFormWidth || '50%'
    this.viewFormTitle = viewObj.viewFormTitle
    this.flagFullTxtSearch = viewObj.flagFullTxtSearch || false
    this.fullSearchFields = viewObj.fullSearchFields || []
    if (this.flagFullTxtSearch) {
      let flagFullTxtTitleArr = []
      viewObj.columns.filter(column => this.fullSearchFields.includes(column.name)).forEach(column2 => flagFullTxtTitleArr.push(column2.title))
      this.flagFullTxtTitle = flagFullTxtTitleArr.join('/')
    }
    // this.viewFormStyle = viewObj.viewFormStyle
    this.viewButtons = viewObj.viewButtons || []
    this.rowButtons = viewObj.rowButtons || []
    this.rules = this.parseRules(viewObj.rules)
    this.baseColumns = viewObj.baseColumns || []
    this.dataFilterType = viewObj.dataFilterType || null
    this.dataFilterField = viewObj.dataFilterField || null
    // 明细界面的内容
    this.viewFormButtons = viewObj.viewFormButtons || []
    this.viewKeyDb = viewObj.viewKey
    this.viewName = viewObj.viewName
    this.importViewKey = viewObj.importViewKey
    this.importTableName = 'import_temp_' + viewObj.viewKey
    this.viewFormDictionaryDef = viewObj.viewFormDictionaries || []
    // 各类按钮设定
    this.configReserveButtons = viewObj.configReserveButtons || []
    this.searchGroupFields = viewObj.searchGroupFields || []

    if (this.searchGroupFields && this.strings.isString(this.searchGroupFields)) this.searchGroupFields = this.searchGroupFields.split(',')
    //按钮节点配置
    this.btnNodeMap = viewObj.btnNodeMap || {}
    if (this.strings.isNotBlank(this.propPageSize)) {
      if (this.tablePageSizes.indexOf(this.propPageSize) == -1) {
        this.tablePageSizes.push(this.propPageSize)
      }
      this.tablePage.pageSize = this.propPageSize
    }
    this.addDefaultButtons()
    this.customColums()

    if (this.columns && this.columns.length > 0) {
      this.userQuery = this.columns.filter((item) => this.strings.isNotBlank(item.queryType) && item.queryType !== 'none')
      //包含列表查询排序的话，则进行排序
      if (this.userQuery && this.userQuery.length > 0 && this.userQuery[0].sortQuery) {
        this.userQuery.sort((left, right) => {
          return this.strings.defaultIfBlank(left.sortQuery, 999) - this.strings.defaultIfBlank(right.sortQuery, 999)
        })
      }
      if (!this.cpDisabledDateFirst && this.userQuery && this.userQuery.length > 0 ) {
        let dateFirst = this.userQuery.findIndex(item => item.queryType && item.queryType =='dateArea')
        if (dateFirst != -1 && this.utilDataview.isAddDateFirst(this.propViewKey)) {
            this.dateFirstName = this.userQuery[dateFirst].name
            let fieldLabel = this.utilFieldMap.show(this.userQuery[dateFirst].name,this.userQuery[dateFirst].title,'dataview',this.propViewKey)
            // this.tableFormState[this.dateFirstName] = this.dates.getDateBeforeDays(this.constCommon.dataViewDefaultDateBefore)
            // this.tableFormState[this.dateFirstName+'1'] = new Date().format(this.dates.defaultDatePattern) + ' 23:59:59'
            this.tableFormState[this.dateFirstName] = [
              this.dates.getDateBeforeDays(this.constCommon.dataViewDefaultDateBefore),
              new Date().format(this.dates.defaultDatePattern) + ' 23:59:59'
            ]
            setTimeout(() => {
              // this.utilMessage.warning(`已默认显示${fieldLabel} 从 ${this.tableFormState[this.dateFirstName]} 到 ${this.tableFormState[this.dateFirstName+'1']} 的相关数据`, 5000)
            }, 500)
        }
      }
    }

    //行样式表达式
    if (this.formConfig.rowAlertEval) {
      let fun = eval('(row) => { return ' + this.formConfig.rowAlertEval + '}')
      this.rowAlertFun = fun
      if (this.strings.isNotBlank(this.formConfig.rowAlertMsg)) {
        setTimeout(() => {
          this.utilMessage.warning(this.formConfig.rowAlertMsg)
        }, 3000)
      }
    }

    // 外部调用刷新数据时有可能结构还没就绪，此时应该设置预约刷新数据标志isBookedData，并不直接刷新数据
    // if (this.isBookedData) {
    //   if (autoReload) {
    //     this.fetchData(this.strings.isNotBlank(this.propPageSize), true)
    //   } else {
    //     this.insertFirst()
    //   }
    // } else {
    //   this.listLoading = false
    //   this.insertFirst()
    // }

    // 暂时放在此处加载
    this.fetchDict()
    // this.$nextTick(() => {
    //   this.$emit('view-ready')
    // })
  },
  // 获取主列表数据功能
  fetchData(isHandlePageChange, isByStru, isPageSearch) {
    // 没有入口，说明还没有加载好结构，交给结构加载好去执行
    if (!this.listEntry) {
      this.isBookedData = true
      return
    }

    // 检测条件中是否存在 1 != 1，如果存在，直接清空数据，不请求后台
    if (
      this.queryWrappers.detectOneNeOne(this.propPreQueryWrapper)
      || this.queryWrappers.detectOneNeOne(this.queryWrapper)
    ) {
      this.rows = []
      this.rows0 = []
      this.tablePage.totalResult = 0
      this.listLoading = false
      this.$refs.tbMain.loadData(this.rows)
      this.insertFirst()
      return
    }
    if (isByStru != true || this.listLoading != true) this.listLoading = true
    //  加载前回调,可以回传过滤条件，事件回调为异步，不可以在这个方法中设置过滤条件
    this.$emit('before-load', (val) => {

    })

    //非下拉表格时为了减少纵向滚动条，每页数量动态
    if (this.showPagination && (isHandlePageChange != true) && this.$refs.tbMain && this.$refs.tbMain.$el && $(this.$refs.tbMain.$el).closest('.my-dropdown4').length == 0) {
      let tbMain = $(this.$refs.tbMain.$el)
      let xh = $(window).height() - tbMain.offset().top - 170
      let pageSize = Math.round(xh / 37)
      if (pageSize < 3) pageSize = 5
      if (this.tablePageSizes.indexOf(pageSize) == -1) {
        this.tablePageSizes.push(pageSize)
      }
      this.tablePage.pageSize = pageSize
    }
    this.tablePageSizes.sort((a, b) => a - b)
    if (!isHandlePageChange || isHandlePageChange != true) {
      //如果存储了，则取存储的分页数量
      let pageSizeStore = localStorage.getItem('dataview_pagesize_' + this.propViewKey)
      if (pageSizeStore && !isNaN(pageSizeStore)) {
        this.tablePage.pageSize = parseInt(pageSizeStore, 0)
      }
      // 如果 页面设置了每页显示数量,使用页面设置的数量
      if (this.propPageSize && !isNaN(pageSizeStore) && this.strings.isNotBlank(this.propPageSize)) {
        this.tablePage.pageSize = this.propPageSize
      }
    }

    try {
      this.$refs.tbMain.clearActived()
      // eslint-disable-next-line no-empty
    } catch (e) {
    }
    let that = this
    const {reqType, reqParam} = this.getFetchReqParams(isByStru)
    let getUrl = this.listEntry
    if (this.viewType && this.viewType == 'import') {
      getUrl = '/tool/pageForImportTmpTable'
    }
    this.$ajax[reqType](getUrl, reqParam).then((response) => {
      // 赋值：rows 行数据，columns 列定义，settings 配置信息（包括命令按钮等）
      if (!response.data || response.data.length < 1) {
        this.rows = []
        this.rows0 = []
      } else {
        this.rows = global.utils.jsonClone(response.data)
        this.rows0 = global.utils.jsonClone(response.data)
        //前端排序
        let sortColumns = this.columns.filter(column => column.sortable == 'true')
        sortColumns.forEach(column => {
          this.rows = this.rows.sort((row1, row2) => (column.defaultSort == 'descending' ? row2[column.name] - row1[column.name] : row1[column.name] - row2[column.name]))
        })
      }
      this.tablePage.totalResult = parseInt(response.count == null ? response.data.length : response.count, 10)
      this.$refs.tbMain.loadData(this.rows)

      //当前页大于0，但是当前页没数据的时候，往前移动一页
      if (this.tablePage.totalResult > 0 && this.rows0.length < 1 && this.tablePage.currentPage > 1) {
        let currentPageTo = this.tablePage.currentPage - 1
        if (currentPageTo < 1) currentPageTo = 1
        this.tablePage.currentPage = currentPageTo
        this.fetchData(true)
        this.insertFirst()
        return
      }

      // 加载完回调
      this.$nextTick(() => {
        let params = this.$route.params
        let autoQuery = 'autoQuery'
        if (params[autoQuery] != null && params[autoQuery] == true) {
          Object.keys(params).forEach((key) => {
            if (Object.prototype.hasOwnProperty.call(params, key)) {
              if (this.primaryKey == key) {
                //主键直接显示
                this.viewRow(params[key])
                delete this.$route.params[key]
              }
            }
          })
        } else if (this.viewFormVisible && (this.autoOpenFirst || this.autoOpenLast)) { //直接显示第一条数据
          this.currentRow = this.rows[this.autoOpenFirst ? 0 : this.tablePage.pageSize - 1]
          this.setCurrent(this.currentRow)
          this.refreshCurrentRow(this.currentRow, true)
          this.autoOpenFirst = false
          this.autoOpenLast = false
        }
        this.insertFirst()
        this.$emit('after-load', this.rows, this.propViewKey)
        // this.handlePageSearch()

        //去掉未选中的行的选中样式
        $(this.$refs.tbMain.$el).find('.vxe-cell--checkbox').each(function () {
          let tr = $(this).closest('tr')
          let checkBox = $(this)
          if (!checkBox.hasClass('is--checked')) {
            tr.removeClass('row-check')
          } else {
            tr.addClass('row-check')
          }
        })
        this.searchGroupDisabled = false
        this.isAfterFetchData = true

        //加载完进行页面搜索
        if (isPageSearch && isPageSearch == true) {
          this.handlePageSearch()
        }

        //定时刷新数据
        this.autoFetchCycleOp('1', '已开启定时刷新')
      })
    }).finally(() => {
      this.listLoading = false
    })

    // setTimeout(() => {
    //   this.loadGroupUrl()
    // }, 500)
    this.sumTop()
  },
  // 网格选中行发生变化时触发
  handleCellClick(param) {
    this.editRow = param.row
    this.editCell = param.cell
    this.editColumnName = param.column.property
    if (!this.editColumnName || !param.column || !param.column.editRender || !param.column.editRender.name) {
      return
    }
    //手动聚焦
    this.focusCellForEdit(param.column.editRender.name)
  },
  // 网格选中行发生变化时触发
  handleCurrentRowChange(row, oldRow) {
    // 单选
    if (this.cpShowRadiobox) {
      this.getGrid().setRadioRow(row.row)
    } else if (this.cpShowCheckbox) { //多选
      this.getGrid().toggleCheckboxRow(row.row)
    }
    this.currentRow = row.row || {}
    let pkvalue = row[this.primaryKey]
    if (pkvalue) {
      let childrenGrid = this.$refs[pkvalue][0]
      if (childrenGrid) {
        childrenGrid.setAllCheckboxRow(true)
      }
    }

    this.$emit('current-change', {row, oldRow, viewKey: this.propViewKey})
  },
  // 网格选中行发生变化时触发
  handleCheckboxChange(param) {
    this.checkChildGrid([param.row], param.checked)
    this.$emit('checkbox-change', param)
  },
  // 查询按钮事件
  handleQueryClick() {
    /*if (this.flowNodes && this.flowNodes.length > 0 && this.flowNodeValue == null) {
      this.flowNodeValue = this.flowNodes[0].value
    }*/
    let params = this.$route.params
    let wrapper = this.$newWrapper()
    let autoQuery = 'autoQuery'
    Object.keys(params).forEach((key) => {
      if (Object.prototype.hasOwnProperty.call(params, key) && key != autoQuery) {
        if (Array.isArray(params[key])) {
          wrapper.in(key, params[key])
        } else {
          wrapper.eq(key, params[key])
        }
      }
    })
    if (params[autoQuery] != null && params[autoQuery] == true) {
      this.queryWrapperOnce = wrapper
    }
    this.tablePage.currentPage = 1
    this.fetchData()
  },
  // 网格选中行发生变化时触发
  handleCheckboxAll(param) {
    this.checkChildGrid(param.records, param.checked)
    this.$emit('checkbox-all', param)
  },
  // 子网格选中行发生变化时触发
  handleChildCheckboxAll(param) {
    param.$grid.data.forEach(ob => {
      ob.checked = param.checked
    })
    this.afterChildCheckChange(param)
  },
  //子格选中行发生变化时触发
  handleChildCheckboxChange(param) {
    param.row.checked = param.checked
    this.afterChildCheckChange(param)
  },
  //子格变化后，级联变化主网格主数据
  afterChildCheckChange(param) {
    let checkOne = param.$grid.data.findIndex(ob => ob.checked && ob.checked == true) != -1
    let parentId = param.$grid.params.parentId
    if (checkOne) { //有一个选中，则选中主数据
      this.$refs.tbMain.setCheckboxRow(param.$grid.params.parentRows, true)
    } else { //没有一个选中，则取消选中主数据
      this.$refs.tbMain.setCheckboxRow(param.$grid.params.parentRows, false)
    }
    console.log('checkOne', checkOne)

    this.$emit('checkbox-change', {row: param.$grid.params.parentRows, checked: checkOne})
  },

  //选中或者取消选中子网格
  checkChildGrid(rowsMain, checked) {
    if (rowsMain && rowsMain.length > 0) { //主数据有被选中的
      rowsMain.forEach(record => {
        let pkvalue = record[this.primaryKey]
        if (pkvalue && this.$refs[pkvalue]) {
          let childrenGrid = this.$refs[pkvalue][0]
          if (childrenGrid) {
            childrenGrid.setAllCheckboxRow(checked)

            record.childData.forEach(ob => ob.checked = checked)
          }
        }
      })
    } else { //没有一个选中的，则取消所有子网格的选中
      this.rows0.forEach(record => {
        let pkvalue = record[this.primaryKey]
        if (pkvalue && this.$refs[pkvalue]) {
          let childrenGrid = this.$refs[pkvalue][0]
          if (childrenGrid) {
            childrenGrid.setAllCheckboxRow(checked)
            record.childData.forEach(ob => ob.checked = checked)
          }
        }
      })
    }
  },
  // 网格双击事件
  handleTableDbClick(row) {
    row = row.row
    if (!row[this.primaryKey] || this.editable || (this.propsDisableDbClick != undefined && this.propsDisableDbClick)) { //可行编辑时禁止双击事件
      return
    }
    const tableDblClickListhener = this.$listeners['table-dbl-click']
    if (tableDblClickListhener) {
      tableDblClickListhener(row)
      return
    }
    let rowButtons = this.cpFilteredButtons(this.rowButtons, row)
    // let rowButtons = this.rowButtons
    if (this.viewForm == null) {
      return
    }
    if (rowButtons.find((item) => item.key === 'vrb-edit')) {
      this.rowEdit(row, false)
    } else {
      this.rowEdit(row, true)
    }
    /*else if (rowButtons.find(item => item.key === 'vrb-view')) {
     this.rowEdit(row, true)
   }*/
  },
  // 自定义选择
  _customSelectFocus(column, row) {
    this.$emit('customSelectFocus', column, row)
  },
  // 自定义选择
  _columnRender(column) {
    this.$set(column, 'isRender', true)
  },

  // 子表格样式
  getChildTableStyle() {
   let style = {marginLeft: '200px'}
   if (this.propChildTableStyle) {
     Object.keys(this.propChildTableStyle).forEach(key => {
       style[key] = this.propChildTableStyle[key]
     })
   }
   return style
  }
}

export default dvFunPrivateGrid
